package com.fwc.fw.util;

import com.fwc.fw.domo.Form;
import com.fwc.fw.domo.FormField;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.TreeMap;

public class FormFactory {

	public static Form getForm(Class clazz) throws Exception {
		Form f = new Form();
		com.fwc.fw.annotation.Form a = (com.fwc.fw.annotation.Form) clazz.getAnnotation(com.fwc.fw.annotation.Form.class);
		if(null!=a) {
			f.setLabel(a.label());
			f.setFields(getFormFields(clazz));
		}
		
		return f;
	}
	
	public static Collection<FormField> getFormFields(Class clazz) throws Exception {
		Field[] fields = clazz.getDeclaredFields();
		TreeMap<Integer, FormField> formFields = new TreeMap<Integer, FormField>();
		for(int i=0; i<fields.length; i++) {
			Field f = fields[i];
			Annotation[] annotations = f.getAnnotations();
			com.fwc.fw.annotation.FormField a = f.getAnnotation(com.fwc.fw.annotation.FormField.class);
			if(a!=null) {
				FormField ff = new FormField(a.label(), f.getType(), a.renderer(), f.getName(), a.canEditDomo());
				ff.setController(a.controller());
				formFields.put(a.order(), ff);
			}
		}
		return formFields.values();
	}

	
}
